package cn.iocoder.yudao.module.scrm.dal.mysql.phoneencryptor;

import java.util.*;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.scrm.dal.dataobject.phoneencryptor.PhoneEncryptorDO;
import org.apache.ibatis.annotations.*;
import cn.iocoder.yudao.module.scrm.controller.admin.phoneencryptor.vo.*;

/**
 * 客户手机加密配置 Mapper
 *
 * @author admin
 */
@Mapper
public interface PhoneEncryptorMapper extends BaseMapperX<PhoneEncryptorDO> {

    default PageResult<PhoneEncryptorDO> selectPage(PhoneEncryptorPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<PhoneEncryptorDO>()
                .likeIfPresent(PhoneEncryptorDO::getUserName, reqVO.getUserName())
                .orderByDesc(PhoneEncryptorDO::getId));
    }

    @Select("SELECT COUNT(*) FROM scrm_phone_encryptor WHERE user_id = #{userId}")
    int existsByUserId(@Param("userId") Long userId);

    @Insert("INSERT INTO scrm_phone_encryptor (user_id, user_name, create_time, creator) VALUES (#{userId}, #{userName}, #{createTime}, #{creator})")
    int insert(PhoneEncryptorDO phoneEncryptorDO);

    @Update("UPDATE scrm_phone_encryptor SET user_id= #{userId},user_name = #{userName}, create_time = #{createTime}, creator = #{creator} WHERE user_id = #{userId}")
    int updateByUserId(PhoneEncryptorDO phoneEncryptorDO);

    default boolean saveOrUpdateByUserId(PhoneEncryptorDO phoneEncryptorDO) {
        // 检查是否存在该 userId 的记录
        int count = existsByUserId(phoneEncryptorDO.getUserId());
        if (count > 0) {
            // 存在则更新
            return updateByUserId(phoneEncryptorDO) > 0;
        } else {
            // 不存在则插入
            return insert(phoneEncryptorDO) > 0;
        }
    }

}